package org.springblade.metadata.service.impl;

import org.apache.atlas.AtlasClientV2;
import org.apache.atlas.AtlasServiceException;
import org.apache.atlas.model.SearchFilter;
import org.apache.atlas.model.typedef.AtlasEntityDef;
import org.apache.atlas.model.typedef.AtlasTypesDef;
import org.springblade.metadata.service.AtlasProxyService;
import org.springblade.metadata.service.TypeSystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TypeSystemServiceImpl implements TypeSystemService {

	@Autowired
	private AtlasProxyService atlasProxyService;

	@Override
	public AtlasTypesDef getAll(SearchFilter searchFilter) {
		AtlasClientV2 client = atlasProxyService.get();

		AtlasTypesDef all = null;
		try {
			all = client.getAllTypeDefs(searchFilter);
		} catch (AtlasServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return all;
	}

	@Override
	public AtlasEntityDef getEntityByName(String name) {
		AtlasClientV2 client = atlasProxyService.get();
		AtlasEntityDef d = null;
		try {
			d = client.getEntityDefByName(name);
		} catch (AtlasServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return d;
	}

	@Override
	public AtlasEntityDef createEntityType(AtlasEntityDef e) throws AtlasServiceException {
//		AtlasClientV2 client = atlasProxyService.get();
//		AtlasEntityDef ee = client.createEntityDef(e);
//		return ee;
		
		AtlasClientV2 client = atlasProxyService.get();
		AtlasTypesDef typesDef = new AtlasTypesDef();
		typesDef.getEntityDefs().add(e);
		typesDef = client.createAtlasTypeDefs(typesDef);
		return typesDef.getEntityDefs().get(0);
	}

	@Override
	public void removeEntityTypeByName(String name) throws AtlasServiceException {
		AtlasClientV2 client = atlasProxyService.get();
		client.deleteTypeByName(name);
	}

	@Override
	public AtlasEntityDef getEntityByGuid(String guid) throws AtlasServiceException {
		AtlasClientV2 client = atlasProxyService.get();
		return client.getEntityDefByGuid(guid);
	}

	@Override
	public AtlasEntityDef update(AtlasEntityDef entityDef) throws AtlasServiceException {
		AtlasClientV2 client = atlasProxyService.get();
		AtlasTypesDef typesDef = new AtlasTypesDef();
		typesDef.getEntityDefs().add(entityDef);
		typesDef = client.updateAtlasTypeDefs(typesDef);
		return typesDef.getEntityDefs().get(0);
	}
}
